# 解析mysql binlog文件，从中根据更新的脚本, 逆向调整为更新前的数据（指定字段）
def parse_binlog(binlog_file_path):
    with open(binlog_file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    update_statements = []
    current_update_statement = ''
    find_count = 0

    for line in lines:
        if line.startswith("### UPDATE `pms_lift`.`lift_info`"):
            current_update_statement = line
            find_count = 0
        elif line.startswith("### WHERE"):

            if find_count == 0:
                find_count = 1
        elif line.startswith("###   @1="):

            if find_count == 1:
                current_update_statement += line
                update_statements.append(current_update_statement)
        elif line.startswith("###   @31"):

            if find_count == 1:
                current_update_statement += line
                update_statements.append(current_update_statement)
                current_update_statement = ''
                find_count = find_count + 1


    return update_statements

def extract_id_and_maintenance_personnel_values(where_clause):
    # 提取@1和@31对应的值
    id_value = None
    maintenance_personnel_value = None

    for line in where_clause.split('\n'):
        if '@1' in line:
            id_value = line.split('=')[1].strip("'")
        elif '@31' in line:
            maintenance_personnel_value = line.split('=')[1].strip("'")

    return id_value, maintenance_personnel_value

def generate_update_script(update_statement):
    # 解析WHERE子句，获取id和maintenance_personnel对应的值
    where_clause_start = update_statement.find("WHERE") + len("WHERE")
    where_clause = update_statement[where_clause_start:].strip()

    # 提取id和maintenance_personnel对应的值
    id_value, maintenance_personnel_value = extract_id_and_maintenance_personnel_values(where_clause)

    # 检查是否成功提取id和maintenance_personnel的值
    if id_value is None or maintenance_personnel_value is None:
        return None

    # 构建原始文件内容
    original_content = (
        f"UPDATE `pms_lift`.`lift_info`\n"
        f"SET maintenance_personnel = '{maintenance_personnel_value}'\n"
        f"WHERE id = '{id_value}';\n"
    )

    return original_content

def main():
    binlog_file_path = "data/0123binlog.sql"
    update_statements = parse_binlog(binlog_file_path)

    for update_statement in update_statements:
        original_content = generate_update_script(update_statement)
        if original_content is not None:
            print(original_content)

if __name__ == "__main__":
    main()
